package com.mystnihon.freeremote.loader.guide;

import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.SystemClock;

import com.mystnihon.freeremote.data.Channel;
import com.mystnihon.freeremote.data.GuideResultData;
import com.mystnihon.freeremote.data.Program;
import com.mystnihon.freeremote.db.DBHelper;
import com.mystnihon.freeremote.util.NetworkConnection;
import com.mystnihon.freeremote.util.NetworkConnectionRequest;
import com.mystnihon.freeremote.util.NetworkConnectionResult;
import com.octo.android.robospice.request.CachedSpiceRequest;
import com.octo.android.robospice.request.SpiceRequest;

public class CachedGuideNetworkRequest extends CachedSpiceRequest<GuideResultData> {

	public static final long CACHE_DURATION_TIME = 3600000l; //un cache d'une demi-heure
	
    public CachedGuideNetworkRequest(Context context, HttpContext hContext, NetworkConnectionRequest request) {
        super(new GuideNetworkRequest(context, hContext, request), request.getCacheKey(), CACHE_DURATION_TIME);
    }

    public static class GuideNetworkRequest extends SpiceRequest<GuideResultData> {
        private final HttpContext mHttpContext;
        private final NetworkConnectionRequest mNetworkConnectionRequest;
        private Context mContext;

        public GuideNetworkRequest(Context context, HttpContext hContext, NetworkConnectionRequest request) {
            super(GuideResultData.class);
            mContext = context;
            mHttpContext = hContext;
            mNetworkConnectionRequest = request;
        }

        @Override
        public GuideResultData loadDataFromNetwork() throws Exception {

            NetworkConnection network = new NetworkConnection();
            network.setHttpContext(mHttpContext);
            NetworkConnectionResult nResult = network.wget(mNetworkConnectionRequest);

            return GuideParser.parse(mContext, nResult.mResult);
        }
    }

    public static class GuideParser {

        public static GuideResultData parse(Context context, String result) throws JSONException {

            System.out.println("JSON : " + result);

            GuideResultData gResult = new GuideResultData();

            JSONObject jsonResult = new JSONObject(result);
            final long lastUpdatetime = SystemClock.currentThreadTimeMillis();

            // List of programs
            JSONObject progsList = jsonResult.optJSONObject("progs");
            if (progsList != null) {
                JSONArray listOfProgsForChannel = progsList.toJSONArray(progsList.names());

                final int size = listOfProgsForChannel.length();
                if (size > 0) {
                    for (int i = 0; i < size; i++) {
                        JSONObject programs = listOfProgsForChannel.optJSONObject(i);
                        if (programs != null) {
                            JSONArray programsForChannels = programs.toJSONArray(programs.names());
                            for (int j = 0; j < programsForChannels.length(); j++) {
                                JSONObject jProgram = programsForChannels.getJSONObject(j);
                                final Program program = new Program(jProgram);
                                gResult.programs.add(program);
                                DBHelper.insertOrUpdateProgram(context.getContentResolver(), program);
                            }
                        }
                    }

                }
            }

            // List of channels
            final JSONObject channelListObject = jsonResult.optJSONObject("chaines");
            if (channelListObject != null) {
                final JSONArray channelListArray = channelListObject.toJSONArray(channelListObject.names());

                final int size = channelListArray.length();
                if (size > 0) {
                    for (int i = 0; i < size; i++) {
                        final Channel channel = new Channel(channelListArray.optJSONObject(i));
                        channel.mLastUpdate = lastUpdatetime;
                        gResult.channels.add(channel);
                        DBHelper.insertOrUpdateChannel(context.getContentResolver(), channel);
                    }
                }
            }

            return gResult;
        }
    }
}
